package aglieBpm.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import aglieBpm.contants.SqlTemplate;
import aglieBpm.entity.BpmConfig;
import aglieBpm.service.BpmConfigService;
import aglieBpm.util.DataBaseUtil;
import aglieBpm.util.RSAUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

@Controller
@RequestMapping("/bpm")
public class BpmController {

	@Resource
	private BpmConfigService bpmConfigService;

	@RequestMapping("/index/{dbName}")
	public String index(@PathVariable String dbName) {
		return "bpmIndex";
	}

	@ResponseBody
	@GetMapping("mytodoList/{pageNum}/{pageSize}/{dbName}")
	public JSONArray mytodoList(@PathVariable String dbName, @PathVariable Integer pageNum, @PathVariable Integer pageSize) {
		Integer pageStart = (pageNum-1) * pageSize ;
		BpmConfig bpmConfig = bpmConfigService.getConfigByDBName(dbName);
		JSONArray jsonArray = DataBaseUtil.excuteSql(bpmConfig.getBpmUrl(), bpmConfig.getBpmUsername(),
				bpmConfig.getBpmPassword(), SqlTemplate.sqlFormat(SqlTemplate._mytodolistlimit10 , pageStart.toString() , pageSize.toString()));
		return jsonArray;
	}

	@ResponseBody
	@GetMapping("allAssigneeUser/{taskId}/{dbName}")
	public JSONArray allAssigneeUser(@PathVariable String taskId, @PathVariable String dbName) {
		BpmConfig bpmConfig = bpmConfigService.getConfigByDBName(dbName);
		JSONArray jsonArray = DataBaseUtil.excuteSql(bpmConfig.getBpmUrl(), bpmConfig.getBpmUsername(),
				bpmConfig.getBpmPassword(), SqlTemplate.sqlFormat(SqlTemplate._listPermissionCode, taskId));

		JSONArray userArr = new JSONArray();
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject object = jsonArray.getJSONObject(i);
			String type = object.getStr("type");
			if (PermissionCodeEnum.org.name().equals(type)) {
				userArr.addAll(
						DataBaseUtil.excuteSql(bpmConfig.getDbUrl(), bpmConfig.getDbUsername(), bpmConfig.getDbPassword(),
								SqlTemplate.sqlFormat(SqlTemplate._receivePhoneTypeOrg, object.getStr("identity"))));
			}
			if (PermissionCodeEnum.user.name().equals(type)) {
				userArr.addAll(
						DataBaseUtil.excuteSql(bpmConfig.getDbUrl(), bpmConfig.getDbUsername(), bpmConfig.getDbPassword(),
								SqlTemplate.sqlFormat(SqlTemplate._receivePhoneTypeUser, object.getStr("identity"))));
			}
			if (PermissionCodeEnum.project.name().equals(type)) {
				userArr.addAll(DataBaseUtil.excuteSql(bpmConfig.getDbUrl(), bpmConfig.getDbUsername(),
						bpmConfig.getDbPassword(),
						SqlTemplate.sqlFormat(SqlTemplate._receivePhoneTypeProject, object.getStr("identity"))));
			}
			if (PermissionCodeEnum.gov.name().equals(type)) {
				userArr.addAll(
						DataBaseUtil.excuteSql(bpmConfig.getDbUrl(), bpmConfig.getDbUsername(), bpmConfig.getDbPassword(),
								SqlTemplate.sqlFormat(SqlTemplate._receivePhoneTypeGov, object.getStr("identity"))));
			}
			if (PermissionCodeEnum.role.name().equals(type)) {
				userArr.addAll(
						DataBaseUtil.excuteSql(bpmConfig.getDbUrl(), bpmConfig.getDbUsername(), bpmConfig.getDbPassword(),
								SqlTemplate.sqlFormat(SqlTemplate._receivePhoneTypeRole, object.getStr("identity"))));
			}
			if (PermissionCodeEnum.projectRole.name().equals(type)) {
				String projectId = object.getStr("identity").split(":")[0];
				String roleId = object.getStr("identity").split(":")[1];
				userArr.addAll(
						DataBaseUtil.excuteSql(bpmConfig.getDbUrl(), bpmConfig.getDbUsername(), bpmConfig.getDbPassword(),
								SqlTemplate.sqlFormat(SqlTemplate._receivePhoneTypeProjectRole, projectId, roleId)));
			}
			if (PermissionCodeEnum.govRole.name().equals(type)) {
				String orgId = object.getStr("identity").split(":")[0];
				String roleId = object.getStr("identity").split(":")[1];
				userArr.addAll(
						DataBaseUtil.excuteSql(bpmConfig.getDbUrl(), bpmConfig.getDbUsername(), bpmConfig.getDbPassword(),
								SqlTemplate.sqlFormat(SqlTemplate._receivePhoneTypeGovRole, orgId, roleId)));
			}
			if (PermissionCodeEnum.company.name().equals(type)) {
				userArr.addAll(DataBaseUtil.excuteSql(bpmConfig.getDbUrl(), bpmConfig.getDbUsername(),
						bpmConfig.getDbPassword(),
						SqlTemplate.sqlFormat(SqlTemplate._receivePhoneTypeCompany, object.getStr("identity"))));
			}
		}
		return userArr;
	}

	@ResponseBody
	@GetMapping("bpmTaskOpinion/{instId}/{dbName}")
	public JSONArray bpmTaskOpinion(@PathVariable String dbName, @PathVariable Long instId) {
		BpmConfig bpmConfig = bpmConfigService.getConfigByDBName(dbName);
		JSONArray jsonArray = DataBaseUtil.excuteSql(bpmConfig.getBpmUrl(), bpmConfig.getBpmUsername(),
				bpmConfig.getBpmPassword(), SqlTemplate.sqlFormat(SqlTemplate._bpmTaskOpinion, instId.toString()));
		return jsonArray;
	}

	@GetMapping("jumpLogin/{userName}/{dbName}")
	public void jumpLogin(@PathVariable String dbName, @PathVariable String userName, HttpServletResponse response) {
		BpmConfig bpmConfig = bpmConfigService.getConfigByDBName(dbName);

		// 登录
		// 获取publicKey api/publicKey
		String publicKeyApi = bpmConfig.getApiUrl() + "api/publicKey";
		String publicKeyResult = HttpUtil.post(publicKeyApi, new HashMap<String, Object>());
		String publicKey = JSONUtil.parseObj(publicKeyResult).getStr("data");

		String loginApi = bpmConfig.getApiUrl() + "api/core/user/pc/auth";
		String rsaUsername = null;
		String rsePassword = null;
		if (bpmConfig.getSuperadminUser().equals(userName)) {
			rsaUsername = RSAUtil.publicEncrypt(userName, publicKey);
			rsePassword = RSAUtil.publicEncrypt(bpmConfig.getSuperadminPwd(), publicKey);
		} else {
			rsaUsername = RSAUtil.publicEncrypt(userName, publicKey);
			rsePassword = RSAUtil.publicEncrypt(bpmConfig.getDefultPassword(), publicKey);
		}
		Map<String, Object> params = new HashMap<>();
		params.put("username", rsaUsername);
		params.put("password", rsePassword);
		String loginResult = HttpUtil.post(loginApi, params);
		String accessToken = JSONUtil.parseObj(loginResult).getJSONObject("data").getStr("authValue");
		response.setHeader("X-Access-Token", accessToken);
		try {
			response.sendRedirect(bpmConfig.getApiUrl()+"jumpPage.html?authValue="+accessToken);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

enum PermissionCodeEnum {
	org, user, project, gov, role, projectRole, govRole, company;
}
